const db = require('../config/db');
const moment = require('moment');

// 日志工具函数
const log = (level, message) => {
  const timestamp = moment().format('YYYY-MM-DD HH:mm:ss');
  console.log(`[${timestamp}] [${level}] ${message}`);
};

/**
 * 获取好友列表
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
exports.getFriends = async (req, res) => {
  try {
    const userId = req.user.id;
    log('INFO', `用户 ${userId} 请求获取好友列表`);

    // 查询好友关系
    const [friendships] = await db.query(
      `SELECT f.friend_id, f.friend_user_id, u.username, CONCAT('http://localhost:5000/', TRIM(LEADING '/' FROM u.avatar_url)) AS avatar_url, u.login
       FROM friends f
       JOIN users u ON f.friend_user_id = u.user_id
       WHERE f.user_id = ? AND f.status = 1`, // status=1 表示已确认的好友
      [userId]
    );

    // 为每个好友获取未读消息数
    const friendsWithUnreadCount = await Promise.all(
      friendships.map(async (friend) => {
        const [unreadResult] = await db.query(
          `SELECT COUNT(*) as unreadCount
           FROM messages
           WHERE receiver_id = ? AND sender_id = ? AND is_read = 0`,
          [userId, friend.friend_user_id]
        );

        return {
          ...friend,
          unreadCount: unreadResult[0].unreadCount
        };
      })
    );

    log('INFO', `用户 ${userId} 成功获取好友列表，共 ${friendsWithUnreadCount.length} 位好友`);
    res.status(200).json({
      success: true,
      friends: friendsWithUnreadCount
    });
  } catch (error) {
    log('ERROR', `获取好友列表失败: ${error.message}`);
    res.status(500).json({
      success: false,
      message: '获取好友列表失败',
      error: error.message
    });
  }
};

/**
 * 获取与特定好友的聊天记录
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
exports.getMessagesByFriendId = async (req, res) => {
  try {
    const userId = req.user.id;
    const { friendId } = req.params;
    log('INFO', `用户 ${userId} 请求获取与好友 ${friendId} 的聊天记录`);

    // 验证好友关系是否存在
    const [friendship] = await db.query(
      `SELECT * FROM friends WHERE user_id = ? AND friend_user_id = ? AND status = 1`,
      [userId, friendId]
    );

    if (friendship.length === 0) {
      log('WARNING', `用户 ${userId} 与 ${friendId} 不是好友关系`);
      return res.status(403).json({
        success: false,
        message: '无权访问此聊天记录'
      });
    }

    // 获取聊天记录
    const [messages] = await db.query(
      `SELECT * FROM messages
       WHERE (sender_id = ? AND receiver_id = ?) OR (sender_id = ? AND receiver_id = ?)
       ORDER BY created_at ASC`,
      [userId, friendId, friendId, userId]
    );

    log('INFO', `用户 ${userId} 成功获取与好友 ${friendId} 的聊天记录，共 ${messages.length} 条消息`);
    res.status(200).json({
      success: true,
      messages
    });
  } catch (error) {
    log('ERROR', `获取聊天记录失败: ${error.message}`);
    res.status(500).json({
      success: false,
      message: '获取聊天记录失败',
      error: error.message
    });
  }
};

/**
 * 标记消息为已读
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
exports.markMessagesAsRead = async (req, res) => {
  try {
    const userId = req.user.id;
    const { friendId } = req.body;
    console.log('INFO', `用户 ${userId} 请求标记与好友 ${friendId} 的消息为已读`);

    // 验证好友关系
    const [friendship] = await db.query(
      `SELECT * FROM friends WHERE user_id = ? AND friend_user_id = ? AND status = 1`,
      [userId, friendId]
    );

    if (friendship.length === 0) {
      log('WARNING', `用户 ${userId} 与 ${friendId} 不是好友关系`);
      return res.status(403).json({
        success: false,
        message: '无权操作此好友的消息'
      });
    }

    // 标记消息为已读
    await db.query(
      `UPDATE messages SET is_read = 1
       WHERE receiver_id = ? AND sender_id = ? AND is_read = 0`,
      [userId, friendId]
    );

    log('INFO', `用户 ${userId} 成功标记与好友 ${friendId} 的消息为已读`);
    res.status(200).json({
      success: true,
      message: '消息已标记为已读'
    });
  } catch (error) {
    log('ERROR', `标记消息为已读失败: ${error.message}`);
    res.status(500).json({
      success: false,
      message: '标记消息为已读失败',
      error: error.message
    });
  }
};

/**
 * 发送消息
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
exports.sendMessage = async (req, res) => {
  try {
    const userId = req.user.id;
    const { receiverId, content } = req.body;
    log('INFO', `用户 ${userId} 尝试发送消息给 ${receiverId}: ${content.substring(0, 20)}...`);

    // 验证好友关系
    const [friendship] = await db.query(
      `SELECT * FROM friends
       WHERE (user_id = ? AND friend_user_id = ? AND status = 1) OR
             (user_id = ? AND friend_user_id = ? AND status = 1)`,
      [userId, receiverId, receiverId, userId]
    );

    if (friendship.length === 0) {
      log('WARNING', `用户 ${userId} 与 ${receiverId} 不是好友关系，无法发送消息`);
      return res.status(403).json({
        success: false,
        message: '只能给好友发送消息'
      });
    }

    // 保存消息到数据库
    const [result] = await db.query(
      `INSERT INTO messages (sender_id, receiver_id, content, friend_id)
       VALUES (?, ?, ?, ?)`,
      [userId, receiverId, content, friendship[0].friend_id]
    );

    // 获取完整的消息对象
    const [message] = await db.query(
      `SELECT * FROM messages WHERE message_id = ?`,
      [result.insertId]
    );

    log('INFO', `用户 ${userId} 成功发送消息给 ${receiverId}，消息ID: ${result.insertId}`);

    // 通过WebSocket发送消息给接收者
    if (global.users[receiverId]) {
      global.io.to(global.users[receiverId]).emit('newMessage', message[0]);
      log('INFO', `消息已通过WebSocket推送给用户 ${receiverId}`);
    } else {
      // 检查数据库中用户的在线状态
      const [userStatus] = await db.query(
        'SELECT login FROM users WHERE user_id = ?',
        [receiverId]
      );
      
      if (userStatus.length > 0 && userStatus[0].login === 1) {
        log('WARN', `用户 ${receiverId} 数据库状态为在线但WebSocket未连接，可能存在连接异常`);
      } else {
        log('INFO', `用户 ${receiverId} 不在线，消息将在其上线后显示`);
      }
    }

    res.status(201).json({
      success: true,
      message: message[0]
    });
  } catch (error) {
    log('ERROR', `发送消息失败: ${error.message}`);
    res.status(500).json({
      success: false,
      message: '发送消息失败',
      error: error.message
    });
  }
};